<template>
  <view class="content">
    <topNotification ref="topNotificationRef" :safe-height="false"></topNotification>
    <!-- 弹窗提示 -->
    <uni-popup ref="alertDialogRef" type="dialog">
      <uni-popup-dialog type="info" cancelText="关闭" confirmText="复制" title="提示" content="点击【复制】立刻导出当前选中的【自定义命令】至剪切板，在其他设备应用上进入【设备详情页】或者首页【批量操作】点击【导入】，输入后点击确定即可。" @confirm="dialogConfirm"></uni-popup-dialog>
    </uni-popup>
    <!-- 配置输入 -->
    <uni-popup ref="inputDialog" type="dialog">
      <uni-popup-dialog ref="inputClose" mode="input" title="输入配置" placeholder="请输入配置" @confirm="dialogInputConfirm"></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup name="importExport">
import { ref } from "vue";
import useComputerStore from "@/store/modules/computer.js";
import _ from "lodash";
import { areArraysEqual } from "@/utils/tools.js";
import { isAuthPass } from "../../../utils/authentication";
const props = defineProps({
  computerInfo: {
    type: Object,
    default: {
      name: "",
      ip: "",
      port: "",
      custom_command: [],
    },
  },
});

const computerStore = useComputerStore();

// 导入配置弹窗实例
const inputDialog = ref();

// 弹窗提示实例
const alertDialogRef = ref();

// 导出配置信息
const dialogConfirm = () => {
  if (isAuthPass()) return;
  uni.setClipboardData({
    data: JSON.stringify(commandList.value),
    success: () => {
      topNotificationRef.value.sendPopupTip({
        type: "success",
        message: "导出成功，已复制至粘贴板！",
      });
    },
    fail: () => {
      topNotificationRef.value.sendPopupTip({
        type: "error",
        message: "导出失败，请检查应用粘贴权限是否给予",
      });
    },
  });
};

//自定义命令按钮
let commandList = ref([]);

//打开输出弹窗
const openAlertDialog = (list) => {
  commandList.value = list;
  alertDialogRef.value.open();
};

//打开输入弹窗
const openInputDialog = () => {
  inputDialog.value.open();
};

//校验配置格式是否正确
const validateArray = (data) => {
  // 判断外层是不是对象
  if (!Array.isArray(data)) {
    return false;
  }
  for (let i = 0; i < data.length; i++) {
    let item = data[i];
    if (Object.prototype.toString.call(item) !== "[object Object]") {
      return false;
    }
    if (!areArraysEqual(Object.keys(item), ["script_id", "script_type", "name", "content", "permission"])) {
      return false;
    }
  }
  return true;
};

// 顶部提示横幅实例
const topNotificationRef = ref();

// 输入弹窗回调事件
const dialogInputConfirm = (val) => {
  if (isAuthPass()) return;
  let formatValue = null;
  try {
    formatValue = JSON.parse(val.trim());
  } catch (err) {
    topNotificationRef.value.sendPopupTip({
      type: "error",
      message: "配置格式不正确",
    });
  }

  if (validateArray(formatValue)) {
    let saveData = [];
    if (props.computerInfo.ip) {
      let index;
      for (let i = 0; i < computerStore.computerList.length; i++) {
        let item = computerStore.computerList[i];
        if (item.ip === props.computerInfo.ip && item.port === props.computerInfo.port) {
          index = i;
          break;
        }
      }
      saveData = _.cloneDeep(computerStore.computerList);

      if (saveData[index]["custom_command"]) {
        let custom_command = _.cloneDeep(saveData[index]["custom_command"]);
        custom_command = _.uniqBy([...custom_command, ...formatValue], "script_id");
        saveData[index]["custom_command"] = custom_command;
      } else {
        saveData[index]["custom_command"] = formatValue;
      }

      computerStore.updateComputerList(saveData);
      topNotificationRef.value.sendPopupTip({
        type: "success",
        message: "配置成功",
      });
    } else {
      saveData = _.cloneDeep(computerStore.commandList);
      saveData = _.uniqBy([...saveData, ...formatValue], "script_id");
      computerStore.updateCommandList(saveData);
      topNotificationRef.value.sendPopupTip({
        type: "success",
        message: "配置成功",
      });
    }
  } else {
    topNotificationRef.value.sendPopupTip({
      type: "error",
      message: "配置格式不正确",
    });
  }
};

defineExpose({ openAlertDialog, openInputDialog });
</script>

<style lang="scss" scoped>
.content {
  .settings-list {
    width: 200px;
    background-color: #fff;
    height: 100vh;
    box-sizing: border-box;
    padding-top: var(--status-bar-height);

    .setting-box {
      height: 100rpx;
      line-height: 100rpx;
      padding-left: 40rpx;
      font-size: 30rpx;
      color: #4f4f4f;
    }
  }
}
</style>
